package org.edu.modules.common.util;

import com.alibaba.nacos.common.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.io.PrintStream;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class JwtUtil
{
    private static final String aesKey = "xtasz";

    public static String BuidJwtString(String userId, String userName)
    {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        Map<String, Object> headMap = new HashMap();
        headMap.put("alg", SignatureAlgorithm.HS256.getValue());
        headMap.put("typ", "JWT");

        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("xtasz");

        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());




        JwtBuilder jwtBuilder = Jwts.builder().setHeader(headMap).claim("userId", userId).claim("userName", userName).signWith(signatureAlgorithm, signingKey);

        long nowTimeMills = System.currentTimeMillis();
        long expiretime = nowTimeMills + 10000L;
        Date date = new Date(expiretime);
        jwtBuilder.setExpiration(date);

        return jwtBuilder.compact();
    }

    public static Claims parseJwt(String jwtString)
    {
        Claims claims = null;
        if (StringUtils.isNotEmpty(jwtString)) {
            claims = (Claims)Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary("xtasz")).parseClaimsJws(jwtString).getBody();
        }
        return claims;
    }

    public static void main(String[] args)
    {
        String userName = "lee";
        String userId = "009";
        String jwdToken = BuidJwtString(userName, userId);
        System.out.println(jwdToken);
        Claims claims = parseJwt(jwdToken);
        System.out.println(claims.get("userName"));
    }
}

